package binary_search.leetcode_4_hard;

public class MergeSolution {
    public static void main(String[] args) {
        int[] a = new int[]{1, 2};
        int[] b = new int[]{3, 4};
        double res = findMedianSortedArrays(a, b);
        System.out.println(res);
    }

    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1.length == 0 && nums2.length == 0) {
            return 0;
        }
        int m = nums1.length;
        int n = nums2.length;
        int len = m + n;
        int[] res = new int[len];
        //合并两个有序数组
        int p1 = 0;
        int p2 = 0;
        int i = 0;
        while (p1 < m && p2 < n) {
            if (nums1[p1] > nums2[p2]) {
                res[i++] = nums2[p2];
                p2++;
            } else {
                res[i++] = nums1[p1];
                p1++;
            }
        }
        //判断哪个数组还有剩余元素，放到新数组中。
        while (p1 == m && p2 < n) {
            res[i++] = nums2[p2++];
        }
        while (p2 == n && p1 < m) {
            res[i++] = nums1[p1++];
        }

        //长度奇偶判断，返回中位数
        if (len % 2 != 0) {
            return res[(0 + len) / 2];
        } else {
            double k = (res[(0 + len - 1) / 2] + (res[(0 + len) / 2])) / 2.0;
            return k;
        }
    }
}
